// ip正则判断
// console.log(/^(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])\.(\d{1,2}|1\d\d|2[0-4]\d|25[0-5])$/.test('1270.0.1'));
var chartData = [], area = "", webSocktLink = null;
var timeFlage = 0;
var TSKID, ProPingRule;
//----------------------------------------weSocket----------------------------
function webSockt(taskId, proPingRule){
    function getJson(taskId, proPingRule){
        $.ajax({
            type: 'POST',
            url: CONTEXT_PATH+'/rest/probeOperationApi/getProvCityPingQuery',
            data: {task_id: taskId, proPingRule: proPingRule},
            success: function(data) {
                timeFlage = 0;
                chinaMap.hideLoading();
                $(".mark_modl").hide();
                chartData = data;
                var chinaData = [];
                for (var i in data) {
                    chinaData.push(data[i][0]);
                }
                chinaMap.setOption({
                    series: [
                        {
                            name: 'china',
                            data: convertData(chinaData)
                        }
                    ]
                });
            },
            error: function(XMLHttpRequest, textStatus, errorThrown) {
                console.log(textStatus + errorThrown)
            }
        });
    }
    var websocket = null;
    //判断当前浏览器是否支持WebSocket
    var url = CONTEXT_WEBSOCKET_URL+'client'+ taskId;
    if ('WebSocket' in window) {
        websocket = new WebSocket(url);
    }
    else {
        alert('当前浏览器 Not support websocket')
    }
    //连接成功建立的回调方法
    websocket.onopen = function () {
        setMessageInnerHTML("WebSocket连接成功");
    }
    //将消息显示在网页上
    function setMessageInnerHTML(innerHTML) {
        console.info(innerHTML);
    }
    //收到消息触发
    websocket.onmessage = function (data) {
            getJson(taskId, proPingRule);
            var newurl = CONTEXT_PATH+'/rest/probeOperationApi/getProvCityPingTable?task_id=' + taskId + '&' + 'proPingRule=' + proPingRule;
            dataTable.ajax.url(newurl).load();
        console.info("调用查询方法！");
    }
    //关闭连接时触发
    websocket.onclose = function (){
        console.log('链接已关闭' + taskId);
    }
    return websocket;
}
//-------------------------------------  获取数据  -----------------------------------------------------*/

// ------------------------------------ 下发任务 ----------------------------------------
$('.start').on('click', function(e) {
    var ip, refresh, delivery;
    ip = $('.ipName').val();
    refresh = $('#refresh').val();
    delivery = $('#delivery').val();
    $(".mark_modl").show();
    chinaMap.showLoading();
    document.getElementById('province').style.display = 'none';
    document.getElementById('map').style.display = 'block';
    chinaMap.resize();
    $.ajax({
        type: 'POST',
        url: CONTEXT_PATH+'/rest/probeTask/probeAdd',
        data: {destaddr: ip, tasktypeid: delivery, rule: refresh, proids: area},
        success: function(data) {
            console.info(data);
            // getJson(data.task_id, delivery, refresh);
            if (webSocktLink) {
                webSocktLink.close();
            }
            TSKID = data.taskid;
            ProPingRule = delivery;
            webSocktLink = webSockt(data.taskid, delivery);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(textStatus + errorThrown)
        }
    });
});




//---------------------------------  处理数据函数  ------------------------------------------------------
//获取城市json
var mapChange = function (city) {
    var maps = 'china';
    switch (city) {
        case '安徽': maps = 'anhui'; break;
        case '澳门': maps = 'aomen'; break;
        case '北京': maps = 'beijing'; break;
        case '重庆': maps = 'chongqing'; break;
        case '福建': maps = 'fujian'; break;
        case '甘肃': maps = 'gansu'; break;
        case '广东': maps = 'guangdong'; break;
        case '广西': maps = 'jiangxi'; break;
        case '贵州': maps = 'guizhou'; break;
        case '海南': maps = 'hainan'; break;
        case '河北': maps = 'hebei'; break;
        case '黑龙江': maps = 'heilongjiang'; break;
        case '河南': maps = 'hebei'; break;
        case '湖北': maps = 'hubei'; break;
        case '湖南': maps = 'hunan'; break;
        case '江苏': maps = 'jiangsu'; break;
        case '江西': maps = 'jiangxi'; break;
        case '吉林': maps = 'jilin'; break;
        case '辽宁': maps = 'liaoning'; break;
        case '内蒙古': maps = 'neimenggu'; break;
        case '宁夏': maps = 'ningxia'; break;
        case '青海': maps = 'qinghai'; break;
        case '山东': maps = 'shandong'; break;
        case '上海': maps = 'shanghai'; break;
        case '山西': maps = 'shanxi'; break;
        case '陕西': maps = 'shanxi1'; break;
        case '四川': maps = 'sichuan'; break;
        case '台湾': maps = 'taiwan'; break;
        case '天津': maps = 'tianjin'; break;
        case '香港': maps = 'xianggang'; break;
        case '新疆': maps = 'xinjiang'; break;
        case '西藏': maps = 'xizang'; break;
        case '云南': maps = 'yunnan'; break;
        case '浙江': maps = 'zhejiang'; break;
    }
    return maps;
};
//处理省内数据
var convertData = function(data) {
    var res = [];
    for (var i = 0; i < data.length; i++) {
        var geoCoord = data[i][0].value;
        if (geoCoord === 0) {
            res.push({
                name: data[i][0].name,
                tooltip: {
                    show: true,
                    trigger: 'item',
                    formatter: function(params) {
                        return ( params.name )
                    }
                },
                itemStyle: {
                    normal: { areaColor: '#5FE79A' },
                    emphasis: { areaColor: '#5FE79A' }
                }
            })
        } else if (geoCoord === 1) {
            res.push({
                name: data[i][0].name,
                tooltip: {
                    show: true,
                    trigger: 'item',
                    formatter: function(params) {
                        return ( params.name )
                    }
                },
                itemStyle: {
                    normal: { areaColor: '#FF5D60' },
                    emphasis: { areaColor: '#FF5D60' }
                }
            })
        } else if (geoCoord === 2) {
            res.push({
                name: data[i][0].name,
                tooltip: {
                    show: true,
                    trigger: 'item',
                    formatter: function(params) {
                        return ( params.name )
                    }
                },
                itemStyle: {
                    normal: { areaColor: '#FCE353' },
                    emphasis: { areaColor: '#FCE353' }
                }
            })
        }
    }
    return res;
};
//处理地市数据
var convertPData = function(data) {
    var res = [];
    for (var i = 0; i < data.length; i++) {
        var geoCoord = data[i].value;
        if (geoCoord === 0) {
            res.push({
                name: data[i].name,
                tooltip: {
                    show: true,
                    trigger: 'item',
                    formatter: function(params) {
                        return ( params.name )
                    }
                },
                itemStyle: {
                    normal: { areaColor: '#5FE79A' },
                    emphasis: { areaColor: '#5FE79A' }
                }
            })
        } else if (geoCoord === 1) {
            res.push({
                name: data[i].name,
                tooltip: {
                    show: true,
                    trigger: 'item',
                    formatter: function(params) {
                        return ( params.name )
                    }
                },
                itemStyle: {
                    normal: { areaColor: '#FF5D60' },
                    emphasis: { areaColor: '#FF5D60' }
                }
            })
        }
    }
    return res;
};

//返回全国地图
var chinaMap = echarts.init(document.getElementById('map'));
var provinceMap = echarts.init(document.getElementById('province'));

//--------------------------------- 全国 -------------------------------------------------------------
//获取地图并展示
$.ajax({
    type: 'GET',
    url: 'json/china.json',
    async: false,
    success: function(chinaJson) {
        echarts.registerMap('china', chinaJson);
        chinaMap.hideLoading();
        ChinaMaps();
    },
    error: function(XMLHttpRequest, textStatus, errorThrown) {
        console.log(textStatus + errorThrown)
    }
});

//显示全国地图
function ChinaMaps() {
    chinaMap.setOption({
        backgroundColor: '#F4F3F4',
        title: {
            text: '中国地图',
            top: 30,
            left: 'center',
            textStyle: { color: 'rgb(22, 24, 35)' }
        },
        tooltip: {
            show: false,
            trigger: 'item'
        },
        geo: {
            map: 'china',
            zoom: 1.2,
            itemStyle: {
                normal: {
                    shadowBlur: 50,
                    shadowColor: 'rgba(0, 0, 0, 0.8)'
                }
            }
        },
        series: [{
            type: 'map',
            map: 'china',
            zoom: 1.2,
            label: {
                normal: { show: false },
                emphasis: { show: false }
            },
            itemStyle: {
                normal: {
                    areaColor: '#F4F3F4',
                    borderColor: '#ccc',
                    shadowBlur: 50,
                    shadowColor: 'rgba(0, 0, 0, 0.3)'
                },
                emphasis: { areaColor: '#F4F3F4', borderColor: '#ccc' }
            },
            data: []
        }]
    });
    //地图点击事件
    chinaMap.on("click", function(params) {
        for (var i in chartData) {
            if (i == params.name) {
                var newurl = CONTEXT_PATH+'/rest/probeOperationApi/getProvCityPingTable?task_id=' + TSKID + '&' + 'proPingRule=' + ProPingRule + '&' + 'provinceName=' + params.name;
                dataTable.ajax.url(newurl).load();
                var provinceData = chartData[i][1];
                var city = mapChange(params.name);
                mapsShow(city,provinceData);
                document.getElementById('map').style.display = 'none';
                document.getElementById('province').style.display = 'block';
                provinceMap.resize();
            }
        }
    });
};

//--------------------------------- 市 -------------------------------------------------------------
//获取省级地图
function mapsShow(city, provinceData) {
    provinceMap.showLoading();
    $.ajax({
        type: 'GET',
        url: './json/' + city + '.json',
        async: false,
        success: function(chinaJson) {
            echarts.registerMap('province', chinaJson);
            provinceMap.hideLoading();
            provinceMaps(provinceData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown) {
            console.log(textStatus + errorThrown)
        }
    });
};

//显示省地图
function provinceMaps(provinceData) {
    console.log(convertPData(provinceData));
    provinceMap.setOption({
        backgroundColor: 'F4F3F4',
        title: {
            text: '省地图',
            top: 30,
            left: 'center',
            textStyle: { color: '#000' }
        },
        tooltip: {
            show: false,
            trigger: 'item',
        },
        geo: {
            map: 'province',
            itemStyle: {
                normal: {
                    shadowBlur: 50,
                    shadowColor: 'rgba(0, 0, 0, 0.8)'
                }
            }
        },
        series: {
            type: 'map',
            map: 'province',
            name: 'pr',
            label: {
                normal: { show: false },
                emphasis: { show: false }
            },
            itemStyle: {
                normal: {
                    areaColor: '#F4F3F4',
                    borderColor: '#ccc',
                    shadowBlur: 50,
                    shadowColor: 'rgba(0, 0, 0, 0.3)'
                },
                emphasis: { areaColor: '#F4F3F4', borderColor: '#ccc' }
            },
            data: convertPData(provinceData)
        }
    });
    provinceMap.on("click", function(params) {
        var newurl = CONTEXT_PATH+'/rest/probeOperationApi/getProvCityPingTable?task_id=' + TSKID + '&' + 'proPingRule=' + ProPingRule;
        dataTable.ajax.url(newurl).load();
        document.getElementById('province').style.display = 'none';
        document.getElementById('map').style.display = 'block';
        chinaMap.resize();
    });
};

//jstree
function selectCity(){
    $.ajax({
        url: CONTEXT_PATH+'/rest/probeOperationApi/getGoodProbeArea',
        type: 'POST',
        dataType: 'json',
        success: function(data){
            $(".jstree_city").jstree({
                "plugins" : ["checkbox"],
                'core': {
                    'data' : data
                }
            });
        }
    });
}
selectCity();
// 选择地市
$(".determin").click(function (){
    var arr = $(".jstree_city").jstree().get_checked();
    area = arr.filter(function (item){
        return item.indexOf('j') === -1;
    }).join(',');
    var textArr = $(".jstree_city").jstree().get_checked(true).map(function (item){
        return item.text;
    });
    $("#area").val(textArr.join('、'));
});


// -------------------DataTables--------------------------------

var dataTable = $('#task_list').DataTable({
    serverSide: true,//服务器模式
    bLengthChange: false,
    searching: false,
    bProcessing : true,//加载效果
    language: {
        "sProcessing": "处理中...",
        "sLengthMenu": "显示 _MENU_ 项结果",
        "sZeroRecords": "没有匹配结果",
        "sInfo": "显示第 _START_ 至 _END_ 项结果，共 _TOTAL_ 项",
        "sInfoEmpty": "显示第 0 至 0 项结果，共 0 项",
        "sInfoFiltered": "(由 _MAX_ 项结果过滤)",
        "sInfoPostFix": "",
        "sSearch": "搜索:",
        "sUrl": "",
        "sEmptyTable": "表中数据为空",
        "sLoadingRecords": "载入中...",
        "sInfoThousands": ",",
        "oPaginate": {
            "sFirst": "首页",
            "sPrevious": "上页",
            "sNext": "下页",
            "sLast": "末页"
        },
        "oAria": {
            "sSortAscending": ": 以升序排列此列",
            "sSortDescending": ": 以降序排列此列"
        }
    },
    ajax: {
        url: CONTEXT_PATH+'/rest/probeOperationApi/getProvCityPingTable',
        type: 'GET'
    },
    columns: [
        { title: "探针ID" },
        { title: "所属省份" },
        { title: "所属地市" },
        { title: "结果" },
        { title: "更新时间" },
        { title: "任务ID"}
    ],
    order: [
    ],
    columnDefs: [
        { orderable: false, targets: 0 }
    ]
});
//窗口关闭、刷新
DeletTask();
function DeletTask(){
    function delettask(taskId){
        $.ajax({
            url: CONTEXT_PATH+'/rest/probeTask/probeDel',
            type: 'POST',
            async: false,
            data: {taskids: taskId},
            success: function (data){
                
            }
        });
    }
    var userAgent = navigator.userAgent; //取得浏览器的userAgent字符串  
    var isOpera = userAgent.indexOf("Opera") > -1; //判断是否Opera浏览器  
    var isIE = userAgent.indexOf("compatible") > -1 && userAgent.indexOf("MSIE") > -1 && !isOpera; //判断是否IE浏览器
    var isIE11 = userAgent.indexOf("rv:11.0") > -1; //判断是否是IE11浏览器
    var isEdge = userAgent.indexOf("Edge") > -1 && !isIE; //判断是否IE的Edge浏览器
    try {
        window.onbeforeunload = function (){
            delettask(TSKID);
        }
    } catch (e) {
        if(!isIE && !isEdge && !isIE11) {//兼容chrome和firefox
            var _beforeUnload_time = 0, _gap_time = 0;
            var is_fireFox = navigator.userAgent.indexOf("Firefox")>-1;//是否是火狐浏览器
            window.onbeforeunload = function (){
                _gap_time = new Date().getTime() - _beforeUnload_time;
                if(_gap_time <= 5){
                    delettask(TSKID);//浏览器关闭
                }else{//浏览器刷新
                    delettask(TSKID);
                }
            }
            window.onbeforeunload = function (){ 
                _beforeUnload_time = new Date().getTime();
                if(is_fireFox){//火狐关闭执行
                    delettask(TSKID);//浏览器关闭
                } 
            };
        }
    }
    
}
